// middleware/auth.js
const jwt = require('jsonwebtoken');
const { pool } = require('../config/db');
const { JWT_SECRET } = process.env;

exports.authenticate = (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      const error = new Error('请先登录（未提供令牌）');
      error.statusCode = 401;
      throw error;
    }

    const token = authHeader.split(' ')[1];
    const decoded = jwt.verify(token, JWT_SECRET);

    // 若后续需要传递头像信息，确保字段名正确
    req.user = {
      id: decoded.id,
      username: decoded.username,
      role: decoded.role
    };

    next();
  } catch (err) {
    if (err.name === 'JsonWebTokenError') {
      err.statusCode = 401;
      err.message = '无效的令牌';
    } else if (err.name === 'TokenExpiredError') {
      err.statusCode = 401;
      err.message = '令牌已过期，请重新登录';
    }
    next(err);
  }
};

exports.isAdmin = (req, res, next) => {
  if (req.user && req.user.role === 1) {
    next();
  } else {
    const error = new Error('没有管理员权限');
    error.statusCode = 403;
    next(error);
  }
};